package com.leyou.gateway.filters;

import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import com.leyou.gateway.config.FilterProperties;
import com.leyou.gateway.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Component
@EnableConfigurationProperties({JwtProperties.class, FilterProperties.class})
public class LoginFilter extends ZuulFilter {


    @Autowired
    private JwtProperties jwtProp;

    @Autowired
    private FilterProperties filterProperties;

    //四种拦截类型，pre ，routing，post，error
    @Override
    public String filterType() {
        return "pre";
    }

    //相当于servlet load-on-startup
    @Override
    public int filterOrder() {
        return 1;
    }

    //返回true表示拦截，返回false不拦截
    @Override
    public boolean shouldFilter() {
        // 获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        // 获取request
        HttpServletRequest request = ctx.getRequest();

        List<String> allowPaths = filterProperties.getAllowPaths();

        //获取请求的uri
        String uri = request.getRequestURI();

        //迭代当前的放行列表如果请求地址在放行列表中直接，放行
        for (String allowPath : allowPaths) {
            if (uri.startsWith(allowPath)){
                return false;
            }
        }


        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //判断是否要拦截

        // 获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        // 获取request
        HttpServletRequest request = ctx.getRequest();
        // 获取token
        String token = CookieUtils.getCookieValue(request, jwtProp.getCookieName());
        // 校验
        try {
            // 校验通过什么都不做，即放行
            JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey());
        } catch (Exception e) {
            // 校验出现异常，返回401
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
        }
        return null;
    }
}
